﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Framework.Unity
{
    public class InstanceHoldingContainer : IContainer, IDisposable
    {
        private readonly IContainer _factoryContainer;

        public InstanceHoldingContainer(IContainer factoryContainer)
        {
            _factoryContainer = factoryContainer;
        }

        private readonly IList<object> _objects = new List<object>();
        private bool _disposed;

        public IEnumerable<T> GetAll<T>()
        {
            return _objects.Where(o => o is T).Cast<T>();
        }

        public object GetA(Type contractType)
        {
            return _objects.FirstOrDefault(x => contractType.IsInstanceOfType(x))
                   ?? RegisterAnInstance(_factoryContainer.GetA(contractType));
        }

        public object GetA(Type contractType, IDictionary arguments)
        {
            return _objects.FirstOrDefault(x => contractType.IsInstanceOfType(x))
                   ?? RegisterAnInstance(_factoryContainer.GetA(contractType, arguments));
        }

        public void Release(object instance) { }

        public object RegisterAnInstance(object instance)
        {
            _objects.Add(instance);
            return instance;
        }

        public void Dispose()
        {
            Dispose(true);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (_disposed) return;
            if (disposing)
            {
                if (_objects != null)
                {
                    foreach (var obj in _objects)
                    {
                        Container.Release(obj);
                    }
                }
                GC.SuppressFinalize(this);
            }
            else
            {
                throw new InvalidOperationException(string.Format("Must dispose of all instances of {0}", GetType().FullName));
            }
            _disposed = true;
        }
    }
}